package com.zy.studentSide.controller;

import com.zy.studentSide.entity.*;
import com.zy.studentSide.entity.dto.StudentScourse;
import com.zy.studentSide.entity.ov.UploadFileId;
import com.zy.studentSide.service.IStudentCourseService;
import com.zy.studentSide.service.IStudentService;
import com.zy.studentSide.service.IStudentTaskFileService;
import com.zy.studentSide.service.IStudentTaskService;
import com.zy.teacherSide.entity.*;
import com.zy.teacherSide.entity.dto.TaskDTO;
import com.zy.teacherSide.service.*;
import com.zy.util.DateUtil;
import com.zy.util.R;
import com.zy.util.RandomNum;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author 29787
 */
@RestController
public class StudentTaskController {

    @Autowired
    private ITeacherEnclosureService iTeacherEnclosureService;

    @Autowired
    private IClassroomService iClassroomService;

    @Autowired
    private ICourseService iCourseService;

    @Autowired
    private IStudentCourseService iStudentCourseService;

    @Autowired
    private ITeacherTaskService iTeacherTaskService;

    @Autowired
    private ITeacherService iTeacherService;

    @Autowired
    private IStudentService iStudentService;

    @Autowired
    private IStudentTaskFileService iStudentTaskFileService;

    @Autowired
    private IStudentTaskService iStudentTaskService;

    @Autowired
    private IStudentTaskAchievementService iStudentTaskAchievementService;

    UploadFileId ufi = new UploadFileId();

    /**
     * 学生查看所有作业信息
     *
     * @param studentId
     * @return R
     */
    @PostMapping
    @RequestMapping(value = "/studentGeAllTaskByStudentId/{studentId}")
    public R studentGeAllTask(@PathVariable Integer studentId) throws ParseException {
        //根据学生id查询所有学生课程信息
        List<StudentCourse> allStudentCourse = iStudentCourseService.getAllStudentCourse(studentId);
        List<TaskDTO> allList = new ArrayList<TaskDTO>();
        //判断当前学生是否已选课
        if (allStudentCourse.size() != 0) {
            for (StudentCourse sc : allStudentCourse) {
                List<TeacherTask> ltt = iTeacherTaskService.getTaskCourseIdAndClassroomId(sc.getCourseId(), sc.getClassroomId());
                for (TeacherTask tt : ltt) {
                    TaskDTO taskDTO = new TaskDTO();
                    //封装作业信息
                    taskDTO.setTaskId(tt.getTaskId());
                    taskDTO.setTaskName(tt.getTaskName());
                    taskDTO.setStartTime(tt.getStartTime());
                    taskDTO.setEndTime(tt.getEndTime());
                    taskDTO.setTaskDescribe(tt.getTaskDescribe());

                    // 判断作业提交情况
                    StudentTask studentTask = iStudentTaskService.getStudentTask(tt.getClassroomId(), studentId, tt.getTaskId(), tt.getTeacherId(), tt.getCourseId());
                    if (studentTask != null) {
                        taskDTO.setStudentSubmitStatus("已提交");
                    } else {
                        taskDTO.setStudentSubmitStatus("未提交");
                    }

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    // 今天的时间
                    Date today = new Date();
                    if (DateUtil.comparisonDate(sdf.parse(tt.getStartTime()), today)) {
                        taskDTO.setStatus("作业未开始");
                    } else if (DateUtil.comparisonDate(today, sdf.parse(tt.getEndTime()))) {
                        taskDTO.setStatus("作业已截止");
                    } else {
                        taskDTO.setStatus("作业正在进行");
                    }
                    //封装教师信息
                    Teacher teacher = iTeacherService.getTeacherByTeacherId(tt.getTeacherId());
                    taskDTO.setTeacherName(teacher.getTeacherName());
                    taskDTO.setTeacherId(teacher.getTeacherId());
                    //封装课程信息
                    Course c = iCourseService.getAllCourseByCourseId(sc.getTeacherId(), sc.getCourseId());
                    taskDTO.setCourseName(c.getCourseName());
                    taskDTO.setCourseId(c.getCourseId());
                    //封装班级信息
                    Classroom classroom = iClassroomService.getClassroomByClassroomId(tt.getClassroomId());
                    taskDTO.setClassroomName(classroom.getClassroomName());
                    taskDTO.setNumberPersonsDue(classroom.getClassroomPeopleNum());
                    taskDTO.setClassroomId(classroom.getClassroomId());
                    //封装附件信息
                    TeacherEnclosure te = iTeacherEnclosureService.getTeacherEnclosureById(tt.getTeacherId(), tt.getEnclosureId());
                    taskDTO.setEnclosureId(te.getEnclosureId());
                    if (te == null){
                        taskDTO.setEnclosureName("该作业老师未上传附件");
                    }else{
                        taskDTO.setEnclosureName(te.getOriginalFileName());
                    }
                    allList.add(taskDTO);
                }
            }
            return new R(true,allList);
        } else {
            return new R(false, null);
        }


    }

    /**
     * 学生上传作业
     * @param st
     * @param studentId
     * @return R
     */
    @PostMapping
    @RequestMapping(value = "/studentSubmitTask/{studentId}")
    public R getStudentTask(@RequestBody StudentTask st, @PathVariable Integer studentId){
        Integer id = RandomNum.getRandomID(6);
        st.setUploadFileId(id);
        st.setStudentId(studentId);
        ufi.setUploadFileId(id);
        ufi.setTaskId(st.getTaskId());
        st.setStudentSubmitStatus("已提交");

        boolean b = iStudentTaskService.save(st);
        TeacherTask tt = iTeacherTaskService.getTeacherTaskByTaskId(st.getCourseId(), st.getTaskId(), st.getTeacherId(), st.getClassroomId());
        if (b){
            tt.setTaskSubmitNumber(tt.getTaskSubmitNumber() + 1);
        } else {
            tt.setTaskSubmitNumber(tt.getTaskSubmitNumber());
        }

        return new R(iTeacherTaskService.updateById(tt));
    }


    /**
     * 接收学生上传的作业附件
     * @param file
     * @param request
     * @param studentId
     * @return R
     */
    @PostMapping
    @RequestMapping(value = "/studentUploadFile/{studentId}")
    public R studentUploadFile(@RequestParam("studentUploadFile") MultipartFile file, HttpServletRequest request,
                               @PathVariable Integer studentId) throws Exception {
        //获取文件原始名称
        String oldFlieName = file.getOriginalFilename();
        //获取文件后缀
        String extension = "." + FilenameUtils.getExtension(file.getOriginalFilename());
        //生成新的文件名称
        String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString().replace("-", "") + extension;
        //文件大小
        long size = file.getSize();
        //文件类型
        String type = file.getContentType();
        //目录
        String realPath = ResourceUtils.getURL("classpath:").getPath() + "static/student_task";
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dateDirPath = realPath + "/" + date;
        File dateDir = new File(dateDirPath);
        if (!dateDir.exists()) dateDir.mkdirs();

        //文件上传
        file.transferTo(new File(dateDir, newFileName));

        StudentTaskFile stf = new StudentTaskFile();
        stf.setUploadFilePath(date);
        stf.setStudentId(studentId);
        stf.setOriginalFileName(oldFlieName);
        stf.setContentType(type);
        stf.setUploadFileSize((int)size);
        stf.setUploadFileName(newFileName);
        //获取当前时间
        String currentDate = DateUtil.getCurrentDate();
        stf.setUploadFileTime(currentDate);
        stf.setUploadFileId(ufi.getUploadFileId());
        stf.setTaskId(ufi.getTaskId());

        return new R(iStudentTaskFileService.save(stf));
    }

    /**
     * 学生查看作业成绩
     * @param studentId
     * @param tDTO
     * @return R
     */
    @PostMapping
    @RequestMapping(value = "/studentGetAchievement/{studentId}")
    public R studentGetAchiement(@PathVariable Integer studentId, @RequestBody TaskDTO[] tDTO){

        List<StudentScourse> ss_list = new ArrayList<>();
        for(int i = 0;i < tDTO.length;i++){
            List<StudentTaskAchievement> stat = iStudentTaskAchievementService.getStudentTaskAchievement(tDTO[i].getCourseId(), tDTO[i].getTaskId(), tDTO[i].getTeacherId(), tDTO[i].getClassroomId(), studentId);
            for (StudentTaskAchievement sta : stat){
                StudentScourse ss = new StudentScourse();
                // 封装成绩
                ss.setAchievement(sta.getAchievement());

                // 查询学生信息
                Student s = iStudentService.getStudentByStudentId(studentId);
                ss.setStudentName(s.getStudentName());
                ss.setStudentNum(s.getStudentNum());

                // 查询教师信息
                Teacher t = iTeacherService.getTeacherByTeacherId(tDTO[i].getTeacherId());
                ss.setTeacherName(t.getTeacherName());

                // 查询课程信息
                Course c = iCourseService.getAllCourseByCourseId(tDTO[i].getTeacherId(), tDTO[i].getCourseId());
                ss.setCourseName(c.getCourseName());

                // 查询班级信息
                Classroom classroom = iClassroomService.getClassroomByClassroomId(tDTO[i].getClassroomId());
                ss.setClassroomName(classroom.getClassroomName());

                // 查询作业信息
                TeacherTask tt = iTeacherTaskService.getTeacherTask(tDTO[i].getCourseId(), tDTO[i].getTeacherId(), tDTO[i].getClassroomId());
                ss.setTaskName(tt.getTaskName());

                ss_list.add(ss);
            }
        }
        return new R(true,ss_list);
    }

    /**
     * 学生查看作业成绩
     * @param studentId
     * @param tDTO
     * @return R
     */
    @PostMapping
    @RequestMapping(value = "/studentGetAchievementToEcharts/{studentId}")
    public R studentGetAchievementToEcharts(@PathVariable Integer studentId, @RequestBody TaskDTO[] tDTO){

        StudentAchievementEcharts sae = new StudentAchievementEcharts();
        String[] name = new String[tDTO.length];
        Integer[] achievement = new Integer[tDTO.length];

        for(int i = 0;i < tDTO.length;i++){
            List<StudentTaskAchievement> stat = iStudentTaskAchievementService.getStudentTaskAchievement(tDTO[i].getCourseId(), tDTO[i].getTaskId(), tDTO[i].getTeacherId(), tDTO[i].getClassroomId(), studentId);
            for(int j = 0;j < stat.size();j++){
                if(stat.get(j).getAchievement() == null){
                    achievement[j] = 0;
                }else {
                    achievement[j] = stat.get(j).getAchievement();
                }
            }
            // 查询作业信息
            TeacherTask tt = iTeacherTaskService.getTeacherTask(tDTO[i].getCourseId(), tDTO[i].getTeacherId(), tDTO[i].getClassroomId());
            name[i] = tt.getTaskName();
        }
        sae.setStudentAchievement(achievement);
        sae.setTaskName(name);
        return new R(true,sae);
    }

}
